package com.ruoyi.management.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.management.base.config.TemplateMessageSender;
import com.ruoyi.management.pojo.entity.BatchUserInfoResponse;
import com.ruoyi.management.service.TemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/template")
@RestController
@Api(tags = "微信模板发送接口")
public class TemplateController extends BaseController {

    @Autowired
    private TemplateService templateService;

    // 每次批量拉取OpenID的最大数量（微信限制）
    private static final int OPENID_BATCH_LIMIT = 10000;

    // 每次批量获取用户信息的最大数量（微信限制）
    private static final int USER_INFO_BATCH_LIMIT = 100;

    // 公众号配置信息
    private static final String APPID = "wxf7e6d9100287fbee";
    private static final String APPSECRET = "ab3f6bc69123f6f0656ff1755a64d5ef";
    private static final String TEMPLATE_ID = "nzPu3qirqr3RtCR_cfUfK6FjHJn8_DbuDwasb21HJ1c";

    @ApiOperation(value = "发送账单生成")
    @GetMapping("/sendBilling")
    public AjaxResult sendBilling(@RequestParam String toUserOpenId) {
        try {
            //匹配跟新公众号openid为一方法
            //String accessToken = getWxTemplate();
            String accessToken= "95_Pxwgs1hCbGvBAJeoRdq62FRyzUnaFiiM0w2xkxdvXV4aoxAyZTK55UuDUiWUKPbDqP_XbT2dHjnCAWqicz_WaNHOwq6-C45bfShjaC7Pl-RY3o1fpndMzh6y2McXCVfAHABGZ";
            // 4. 准备并发送模板消息
            String templateId = "2QuPUhAhRJs2sqY0PO2DhLaSfw4bAQsXhbNcfAfwp-0";
            String qymc = "苏州信凯奇信息科技有限公司";
            String hklx = "电表电费";
            String month = "2025-06";
            String je = "9.04";
            String hkrq = "2025-07-15";

            Map<String, TemplateMessageSender.TemplateData> templateData = prepareTemplateData(qymc,hklx,month,je,hkrq);
            sendWechatTemplateMessage(accessToken, toUserOpenId,templateId, templateData);

            log.info("模板消息发送成功");
            return success(templateData);
        } catch (Exception e) {
            log.error("发送模板消息失败：", e);
            return AjaxResult.error("发送模板消息失败：" + e.getMessage());
        }
    }

    //匹配跟新公众号openid为一方法,返回access_token
    public String getWxTemplate() throws Exception{
            // 1. 获取访问令牌
            String accessToken = getAccessToken();
            if (accessToken == null) {
                log.error("获取access_token失败");
            }

            // 2. 获取所有关注用户的OpenID
            List<String> allOpenids = getAllFollowerOpenids(accessToken);
            log.info("获取到公众号关注用户数量：{}", allOpenids.size());

            // 3. 批量获取用户信息(分页处理)
            if (!allOpenids.isEmpty()) {
                batchGetUserInfoByOpenids(accessToken, allOpenids);
            }
        return accessToken;
    }

    /**
     * 获取微信接口访问令牌
     */
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + APPID + "&secret=" + APPSECRET;

        log.info("获取access_token请求地址：{}", url);
        String json = HttpUtils.sendGet(url);
        JSONObject tokenJson = JSON.parseObject(json);

        if (!tokenJson.containsKey("access_token")) {
            log.error("获取access_token失败：{}", json);
            return null;
        }

        return tokenJson.getString("access_token");
    }

    /**
     * 批量获取公众号所有关注用户的OpenID
     */
    public List<String> getAllFollowerOpenids(String accessToken) {
        List<String> allOpenids = new ArrayList<>();
        String nextOpenid = ""; // 分页游标，初始为空表示从第一个用户开始

        do {
            String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken +
                    "&next_openid=" + nextOpenid;
            log.info("获取OpenID列表请求地址：{}", url);

            String response = HttpUtils.sendGet(url);
            JSONObject resultJson = JSON.parseObject(response);

            if (resultJson.containsKey("errcode")) {
                log.error("获取OpenID失败：{}", response);
                break;
            }

            // 提取当前页的OpenID列表
            JSONObject data = resultJson.getJSONObject("data");
            if (data != null && data.containsKey("openid")) {
                JSONArray openidArray = data.getJSONArray("openid");
                for (int i = 0; i < openidArray.size(); i++) {
                    allOpenids.add(openidArray.getString(i));
                }
            }

            // 更新下一页游标
            nextOpenid = resultJson.getString("next_openid");
            log.info("下一页游标：{}", nextOpenid);

        } while (nextOpenid != null && !nextOpenid.isEmpty()); // 直到没有下一页

        return allOpenids;
    }

    /**
     * 根据OpenID列表批量获取用户信息（分页处理）
     */
    public void batchGetUserInfoByOpenids(String accessToken, List<String> allOpenids) throws Exception {
        // 分页处理，每次最多处理100个OpenID（微信限制）
        for (int i = 0; i < allOpenids.size(); i += USER_INFO_BATCH_LIMIT) {
            int end = Math.min(i + USER_INFO_BATCH_LIMIT, allOpenids.size());
            List<String> batchOpenids = allOpenids.subList(i, end);
            log.info("处理第{}批用户，数量：{}", (i / USER_INFO_BATCH_LIMIT + 1), batchOpenids.size());

            String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + accessToken;
            JSONObject postData = createUserInfoRequestData(batchOpenids);

            String jsonResponse = HttpUtils.sendPost(url, postData.toString());
            ObjectMapper objectMapper = new ObjectMapper();
            BatchUserInfoResponse response = objectMapper.readValue(jsonResponse, BatchUserInfoResponse.class);

            // 处理当前批的用户信息
            handleUserInfoResponse(response);
        }
    }

    /**
     * 创建用户信息请求数据
     */
    public JSONObject createUserInfoRequestData(List<String> openids) {
        JSONObject postData = new JSONObject();
        JSONArray userList = new JSONArray();

        for (String openid : openids) {
            JSONObject user = new JSONObject();
            user.put("openid", openid);
            user.put("lang", "zh_CN");
            userList.add(user);
        }


        postData.put("user_list", userList);
        return postData;
    }

//    /**
//     * 处理用户信息响应结果
//     */
//    private void handleUserInfoResponse(BatchUserInfoResponse response) {
//        if (response == null || response.getUser_info_list() == null) {
//            log.info("未获取到用户信息");
//            return;
//        }
//        List<BatchUserInfoResponse.UserInfo> userList = response.getUser_info_list();
//        for (BatchUserInfoResponse.UserInfo user : userList) {
//            log.info("\nOpenID: {}", user.getOpenid());
//
//            // 根据关注状态处理不同的信息
//            if (user.getSubscribe() == 1) {
//                log.info("状态: 已关注");
//                log.info("关注时间: {}", user.getSubscribe_time());
//                log.info("语言: {}", user.getLanguage());
//                log.info("UnionID: {}", user.getUnionid());
//                log.info("所属分组: {}", user.getGroupid());
//            } else {
//                log.info("状态: 未关注");
//            }
//        }
//    }

    // 处理用户信息响应结果（扩展后）
    public void handleUserInfoResponse(BatchUserInfoResponse response) {
        if (response == null || response.getUser_info_list() == null) {
            log.info("未获取到用户信息");
            return;
        }

        List<BatchUserInfoResponse.UserInfo> userList = response.getUser_info_list();
        for (BatchUserInfoResponse.UserInfo user : userList) {
            log.info("\nOpenID: {}", user.getOpenid());

            // 获取用户的UnionID（注意：只有已关注且公众号绑定到开放平台的用户才有UnionID）
            String unionId = user.getUnionid();
            if (unionId == null || unionId.isEmpty()) {
                log.warn("用户[OpenID: {}]未获取到UnionID，无法更新数据库", user.getOpenid());
                continue;
            }

            // 根据关注状态处理（仅已关注用户可能有完整的UnionID）
            if (user.getSubscribe() == 1) {
                log.info("状态: 已关注");
                log.info("关注时间: {}", user.getSubscribe_time());
                log.info("语言: {}", user.getLanguage());
                log.info("UnionID: {}", unionId);
                log.info("所属分组: {}", user.getGroupid());
                // 调用Service更新数据库中的openid
                boolean updateResult = templateService.updateOpenidByUnionId(unionId, user.getOpenid());
                if (!updateResult) {
                    log.error("用户[UnionID: {}]的openid更新失败", unionId);
                }
            } else {
                log.info("状态: 未关注（未关注用户可能无UnionID，跳过更新）");
            }
        }
    }

    /**
     * 处理批量用户信息（取前100个示例）
     * 处理上限是100个，超过100个则取前100个
     */
//    private void handleBatchUserInfo(String accessToken, List<String> allOpenids) throws Exception {
//        // 1. 构建请求URL
//        String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + accessToken;
//
//        // 2. 构建请求参数（使用上面获取到的OpenID列表）
//        List<String> openids = allOpenids.size() > 100 ? allOpenids.subList(0, 100) : allOpenids;
//        JSONObject postData = createUserInfoRequestData(openids);
//
//        // 3. 发送POST请求到微信接口
//        String jsonResponse = HttpUtils.sendPost(url, postData.toString());
//        log.info("微信接口返回原始数据: {}", jsonResponse);
//
//        // 4. 解析JSON响应为实体类对象
//        ObjectMapper objectMapper = new ObjectMapper();
//        BatchUserInfoResponse response = objectMapper.readValue(jsonResponse, BatchUserInfoResponse.class);
//
//        // 5. 处理返回结果
//        handleUserInfoResponse(response);
//    }

    /**
     * 准备模板消息数据
     */
    public Map<String, TemplateMessageSender.TemplateData>
    prepareTemplateData(String qymc, String hklx,String month,String je,String hkrq) {
        Map<String, TemplateMessageSender.TemplateData> data = new HashMap<>();

        // 企业名称
        TemplateMessageSender.TemplateData billType = new TemplateMessageSender.TemplateData();
        billType.setValue(qymc);
        billType.setColor("#173177");
        data.put("thing15", billType);

        // 账单名称
        TemplateMessageSender.TemplateData totalAmount = new TemplateMessageSender.TemplateData();
        totalAmount.setValue(hklx);
        totalAmount.setColor("#173177");
        data.put("thing10", totalAmount);


        // 账单日期
        TemplateMessageSender.TemplateData roomNo = new TemplateMessageSender.TemplateData();
        roomNo.setValue(month);
        roomNo.setColor("#173177");
        data.put("time32", roomNo);

        // 账单金额
        TemplateMessageSender.TemplateData chargeMonth = new TemplateMessageSender.TemplateData();
        chargeMonth.setValue(je);
        chargeMonth.setColor("#173177");
        data.put("amount4", chargeMonth);

        // 应缴日期
        TemplateMessageSender.TemplateData currentReading = new TemplateMessageSender.TemplateData();
        //currentReading.setValue("请您于"+hkrq+"日内完成电费缴纳");
        currentReading.setValue(hkrq);
        currentReading.setColor("#173177");
        data.put("time22", currentReading);
        return data;
    }

    /**
     * 准备模板消息数据
     */
    public Map<String, TemplateMessageSender.TemplateData> prepareTemplateData1() {
        Map<String, TemplateMessageSender.TemplateData> data = new HashMap<>();

        // 用户姓名
        TemplateMessageSender.TemplateData billType = new TemplateMessageSender.TemplateData();
        billType.setValue("用户姓名");
        billType.setColor("#173177");
        data.put("thing49", billType);

        // 账单类型
        TemplateMessageSender.TemplateData totalAmount = new TemplateMessageSender.TemplateData();
        totalAmount.setValue("账单类型");
        totalAmount.setColor("#173177");
        data.put("thing14", totalAmount);


        // 计费月份
        TemplateMessageSender.TemplateData roomNo = new TemplateMessageSender.TemplateData();
        roomNo.setValue("计费月份");
        roomNo.setColor("#173177");
        data.put("time8", roomNo);

        // 总金额
        TemplateMessageSender.TemplateData chargeMonth = new TemplateMessageSender.TemplateData();
        chargeMonth.setValue("总金额");
        chargeMonth.setColor("#173177");
        data.put("amount3", chargeMonth);

        // 最晚缴纳日期
        TemplateMessageSender.TemplateData currentReading = new TemplateMessageSender.TemplateData();
        currentReading.setValue("最晚缴纳日期");
        currentReading.setColor("#173177");
        data.put("time41", currentReading);
        return data;

    }

    /**
     * 发送微信模板消息
     */
    public void sendWechatTemplateMessage(String accessToken, String toUserOpenId,String templateId,
                                           Map<String, TemplateMessageSender.TemplateData> data)
    {
        String url = "";
        TemplateMessageSender.sendTemplateMessage(accessToken, toUserOpenId, templateId, url, data);
    }
}